/**Created by liaoyingchao on 2019-07-16.*/

<template>
  <div class="apppath">
    <div class="full-content-div list-css">
      <div class="top-tools">
        <div class="keys-div">
          <Form ref="formInline" :label-width="80" inline @submit.native.prevent>
            <FormItem label="App名称">
              <i-input type="text" v-model="appName" placeholder="请输入您要搜索App名称" style="width: 200px"></i-input>
            </FormItem>
            <FormItem label="App状态">
              <Select v-model="status" style="width: 120px">
                <Option value="10">所有</Option>
                <Option value="1">启用</Option>
                <Option value="2">禁用</Option>
              </Select>
            </FormItem>
          </Form>
        </div>
        <div class="btns-div">
          <Button type="primary" @click="searchEvent" style="width: 80px;margin: 0 5px;">
            <i class="iconfont iconsearch icon-size"></i>
            查询
          </Button>
          <Button type="primary" @click="newAppPath" style="width: 80px;margin: 0 5px;">
            <i class="iconfont iconadd icon-size"></i>
            新建
          </Button>
        </div>
      </div>
      <div class="table-div" ref="tableDiv">
        <Table stripe :height="tableHeight" :columns="columns" :data="appPathList" v-if="tableShow"></Table>
      </div>
      <div class="footer-tools">
        大于60天未更新的，更新时间为红色，大于20天未更新的，更新时间为黄色
      </div>
    </div>
    <Modal v-model="showModal"
           :mask-closable="false"
           :title="modalType == '1' ? '新建App下载地址' : '编辑App下载地址'"
           class-name="vertical-center-modal modal-css"
           :loading="modalLoading"
           ok-text="保存"
           width="800"
           @on-ok="saveEvent">
      <div class="model-content">
        <div class="info-div">
          <Form :model="appPathInfo" :rules="ruleValidate" :label-width="140" @submit.native.prevent>
            <FormItem label="所属省份" prop="provinceId">
              <Select v-model="appPathInfo.provinceId" @on-change="provinceChange" :disabled="modalType == '2'">
                <Option v-for="(province, idx) in provinceList" :value="province.id" :key="idx">{{ province.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="App Tag" prop="tag">
              <i-input v-model="appPathInfo.tag" placeholder="请输入app tag" :disabled="modalType == '2'"></i-input>
            </FormItem>
            <FormItem label="IOS App下载路径">
              <i-input v-model="appPathInfo.IOSPath" placeholder="请输入IOS App下载路径" @on-blur="iosPathFinished"></i-input>
            </FormItem>
            <FormItem label="IOS App下载密码" v-if="appPathInfo.IOSNeedPwd == '1'">
              <i-input v-model="appPathInfo.IOSPassword" placeholder="请输入Android App下载密码"
                       @on-blur="iosPathFinished"></i-input>
            </FormItem>
            <div class="app-info" v-if="appPathInfo.IOSVersion && appPathInfo.IOSPath">
              <div class="icon">
                <img :src="appPathInfo.IOSIconUrl">
              </div>
              <div>{{appPathInfo.IOSName}}</div>
              <div>版本：{{appPathInfo.IOSVersion}}</div>
              <div>更新时间：{{$util.getFormatTime(appPathInfo.IOSUpdateTime)}}</div>
            </div>
            <FormItem label="Android App下载路径">
              <i-input v-model="appPathInfo.AndroidPath" placeholder="请输入Android App下载路径"
                       @on-blur="androidPathFinished"></i-input>
            </FormItem>
            <FormItem label="Android App下载密码" v-if="appPathInfo.AndroidNeedPwd == '1'">
              <i-input v-model="appPathInfo.AndroidPassword" placeholder="请输入Android App下载密码"
                       @on-blur="androidPathFinished"></i-input>
            </FormItem>
            <div class="app-info" v-if="appPathInfo.AndroidVersion && appPathInfo.AndroidPath">
              <div class="icon">
                <img :src="appPathInfo.AndroidIconUrl">
              </div>
              <div>{{appPathInfo.AndroidName}}</div>
              <div>版本：{{appPathInfo.AndroidVersion}}</div>
              <div>更新时间：{{$util.getFormatTime(appPathInfo.AndroidUpdateTime)}}</div>
            </div>
          </Form>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
  import appinfo from '@/components/appInfo'

  export default {
    name: "apppath",
    components: {
      // eslint-disable-next-line
      appinfo
    },
    data() {
      return {
        provinceList: [{"id":"100","name":"北京市"},{"id":"101","name":"天津市"},{"id":"102","name":"上海市"},{"id":"103","name":"重庆市"},{"id":"104","name":"河北省"},{"id":"105","name":"山西省"},{"id":"106","name":"辽宁省"},{"id":"107","name":"吉林省"},{"id":"108","name":"黑龙江省"},{"id":"109","name":"江苏省"},{"id":"110","name":"浙江省"},{"id":"111","name":"安徽省"},{"id":"112","name":"福建省"},{"id":"113","name":"江西省"},{"id":"114","name":"山东省"},{"id":"115","name":"河南省"},{"id":"116","name":"湖北省"},{"id":"117","name":"湖南省"},{"id":"118","name":"广东省"},{"id":"119","name":"海南省"},{"id":"120","name":"四川省"},{"id":"121","name":"贵州省"},{"id":"122","name":"云南省"},{"id":"123","name":"陕西省"},{"id":"124","name":"甘肃省"},{"id":"125","name":"青海省"},{"id":"126","name":"台湾省"},{"id":"127","name":"内蒙古自治区"},{"id":"128","name":"广西壮族自治区"},{"id":"129","name":"西藏自治区"},{"id":"130","name":"宁夏回族自治区"},{"id":"131","name":"新疆维吾尔自治区"},{"id":"132","name":"香港特别行政区"},{"id":"133","name":"澳门特别行政区"}],
        appName: '',
        status: '10',
        tableHeight: '400',
        tableShow: false,
        modalLoading: true,
        columns: [
          {
            title: 'ID',
            key: 'id',
            width: '60'
          },
          {
            title: '省份',
            key: 'provinceName',
            width: '100'
          },
          {
            title: 'Tag',
            key: 'tag',
            width: '100'
          },
          {
            title: 'IOS Info',
            render: (h, params) => {
              return h('div', [
                h(appinfo, {
                  attrs: {
                    icon: params.row.IOSIconUrl,
                    name: params.row.IOSName,
                    version: params.row.IOSVersion,
                    time: params.row.IOSUpdateTime
                  }
                })
              ]);
            }
          },
          {
            title: 'Android Info',
            render: (h, params) => {
              return h('div', [
                h(appinfo, {
                  attrs: {
                    icon: params.row.AndroidIconUrl,
                    name: params.row.AndroidName,
                    version: params.row.AndroidVersion,
                    time: params.row.AndroidUpdateTime
                  }
                })
              ]);
            }
          },
          {
            title: '操作',
            width: '140',
            render: (h, params) => {
              let arr = []
              arr.push(h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editPathInfo(params.row)
                  }
                }
              }, '编辑'))
              if (params.row.state == '1') {
                arr.push(h('Button', {
                  props: {
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.disablePathInfo(params.row)
                    }
                  }
                }, '禁用'))
              } else if (params.row.state == '2') {
                arr.push(h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.enablePathInfo(params.row)
                    }
                  }
                }, '启用'))
              }
              arr.push(h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px',
                  marginTop: '8px'
                },
                on: {
                  click: () => {
                    this.deletePathInfo(params.row)
                  }
                }
              }, '删除'))
              return h('div', arr);
            }
          }
        ],
        appPathList: [],
        showModal: false,
        modalType: '1',
        appPathInfo: {
          provinceId: '',
          provinceName: '',
          tag: '',
          IOSPath: '',
          IOSNeedPwd: '0',
          IOSPassword: '',
          IOSVersion: '',
          IOSUpdateTime: '',
          IOSIconUrl: '',
          IOSName: '',
          IOSShort: '',
          AndroidPath: '',
          AndroidNeedPwd: '0',
          AndroidPassword: '',
          AndroidVersion: '',
          AndroidUpdateTime: '',
          AndroidIconUrl: '',
          AndroidName: '',
          AndroidShort: '',
        },
        ruleValidate: {
          provinceId: [
            {required: true, message: '请输入必填信息', trigger: 'blur'}
          ],
          tag: [
            {required: true, message: '请输入必填信息', trigger: 'blur'}
          ]
        },
      }
    },
    methods: {
      editPathInfo: function (item) {
        this.appPathInfo = item;
        this.showModal = true;
        this.modalType = '2'
      },
      deletePathInfo: function (item) {
        let url = '/api/appspath/delete';
        this.$http.post(url, {
          id: item.id
        }).then(
          res => {
            let data = res.data;
            if (data.result == '1') {
              console.log(data);
              this.searchEvent()
            } else {
              this.$Message.warning(data.message);
            }
          },
          error => {
            console.log(error)
            this.$Message.error('请求数据出错！');
          }
        );
      },
      disablePathInfo: function (item) {
        let url = '/api/appspath/disable';
        this.$http.post(url, {
          id: item.id
        }).then(
          res => {
            let data = res.data;
            if (data.result == '1') {
              console.log(data);
              this.searchEvent()
            } else {
              this.$Message.warning(data.message);
            }
          },
          error => {
            console.log(error)
            this.$Message.error('请求数据出错！');
          }
        );
      },
      enablePathInfo: function (item) {
        let url = '/api/appspath/enable';
        this.$http.post(url, {
          id: item.id
        }).then(
          res => {
            let data = res.data;
            if (data.result == '1') {
              console.log(data);
              this.searchEvent()
            } else {
              this.$Message.warning(data.message);
            }
          },
          error => {
            console.log(error)
            this.$Message.error('请求数据出错！');
          }
        );
      },
      appInfoParse: function (appInfo) {
        if (appInfo.type == 'ios') {
          this.appPathInfo.IOSPath = 'https://www.betaqr.com/' + appInfo.short
          this.appPathInfo.IOSVersion = appInfo.releases.master.version + '（build：' + appInfo.releases.master.build + '）'
          this.appPathInfo.IOSUpdateTime = appInfo.releases.master.created_at * 1000
          this.appPathInfo.IOSName = appInfo.name
          this.appPathInfo.IOSShort = appInfo.short
          this.appPathInfo.IOSIconUrl = appInfo.icon_url
        } else if (appInfo.type == 'android') {
          this.appPathInfo.AndroidPath = 'https://www.betaqr.com/' + appInfo.short
          this.appPathInfo.AndroidVersion = appInfo.releases.master.version + '（build：' + appInfo.releases.master.build + '）'
          this.appPathInfo.AndroidUpdateTime = appInfo.releases.master.created_at * 1000
          this.appPathInfo.AndroidName = appInfo.name
          this.appPathInfo.AndroidShort = appInfo.short
          this.appPathInfo.AndroidIconUrl = appInfo.icon_url
        }
      },
      getFirMessage: function (path, type) {
        let url = path
        url = url.replace("www.betaqr.com", "fir-download.fircli.cn")
        url = url.replace("fir.im", "fir-download.fircli.cn")
        url = url.replace("tfir.deepermobile.com.cn", "fir-download.fircli.cn")
        console.log(url)
        let params = {}
        if (type == 'ios' && this.appPathInfo.IOSPassword != '') {
          params.Passwd = this.appPathInfo.IOSPassword
        } else if (type == 'android' && this.appPathInfo.AndroidPassword != '') {
          params.Passwd = this.appPathInfo.AndroidPassword
        }
        this.$http.get(url, {
          headers: params
        }).then(
          res => {
            if (type == 'ios') {
              this.appPathInfo.IOSPath = ''
              if (this.appPathInfo.IOSPassword == '') {
                this.appPathInfo.IOSNeedPwd = '0'
              }
            } else {
              this.appPathInfo.AndroidPath = ''
              if (this.appPathInfo.AndroidPassword == '') {
                this.appPathInfo.AndroidNeedPwd = '0'
              }
            }
            let data = res.data;
            console.log(data)
            if (data.auth == true) {
              let app = data.app
              this.appInfoParse(app)
              let combo_app = data.combo_app
              if (combo_app) {
                if (type == 'ios') {
                  this.appPathInfo.AndroidNeedPwd = this.appPathInfo.IOSNeedPwd
                  this.appPathInfo.AndroidPassword = this.appPathInfo.IOSPassword
                } else {
                  this.appPathInfo.IOSNeedPwd = this.appPathInfo.AndroidNeedPwd
                  this.appPathInfo.IOSPassword = this.appPathInfo.AndroidPassword
                }
                this.appInfoParse(combo_app)
              } else {
                // 如果只有一个，并且填写错误，将密码置换过来
                if (app.type != type) {
                  if (type == 'ios') {
                    this.appPathInfo.AndroidNeedPwd = this.appPathInfo.IOSNeedPwd
                    this.appPathInfo.AndroidPassword = this.appPathInfo.IOSPassword
                    this.appPathInfo.IOSNeedPwd = '0'
                    this.appPathInfo.IOSPassword = ''
                  } else {
                    this.appPathInfo.IOSNeedPwd = this.appPathInfo.AndroidNeedPwd
                    this.appPathInfo.IOSPassword = this.appPathInfo.AndroidPassword
                    this.appPathInfo.AndroidNeedPwd = '0'
                    this.appPathInfo.AndroidPassword = ''
                  }
                }
              }
            }
          },
          error => {
            console.log(error)
            let data = error.response.data
            if (data.require_pwd == true) {
              if (type == 'ios') {
                this.appPathInfo.IOSNeedPwd = '1'
              } else {
                this.appPathInfo.AndroidNeedPwd = '1'
              }
              this.$Message.error('请求输入下载密码！');
            } else {
              if (type == 'ios') {
                this.appPathInfo.IOSPath = ''
              } else {
                this.appPathInfo.AndroidPath = ''
              }
              this.$Message.error('请求数据出错！');
            }
          }
        );
      },
      provinceChange: function (value) {
        console.log(value)
        this.appPathInfo.provinceId = value
        this.appPathInfo.provinceName = this.provinceList[(value - 100)].name
      },
      androidPathFinished: function () {
        if (this.appPathInfo.AndroidPath != '') {
          this.getFirMessage(this.appPathInfo.AndroidPath, 'android')
        }
      },
      iosPathFinished: function () {
        if (this.appPathInfo.IOSPath != '') {
          this.getFirMessage(this.appPathInfo.IOSPath, 'ios')
        }
      },
      resetModalLoading: function () {
        this.modalLoading = false
        this.$nextTick(() => {
          this.modalLoading = true
        });
      },
      saveEvent: function () {
        if (this.appPathInfo.provinceId == '' || this.appPathInfo.tag == '') {
          this.$Message.error('请填完所有必填项！');
          this.resetModalLoading()
          return;
        } else if (this.appPathInfo.IOSPath == '' && this.appPathInfo.AndroidPath == '') {
          this.$Message.error('至少一个平台的下载地址！');
          this.resetModalLoading()
          return;
        }
        if (this.modalType == '1') {
          let url = '/api/appspath/addAppPath';
          this.$http.post(url, this.appPathInfo).then(
            res => {
              let data = res.data;
              if (data.result == '1') {
                console.log(data);
                this.showModal = false;
                this.searchEvent()
              } else {
                this.resetModalLoading()
                this.$Message.warning(data.message);
              }
            },
            error => {
              this.resetModalLoading()
              console.log(error)
              this.$Message.error('请求数据出错！');
            }
          );
        } else if (this.modalType == '2') {
          let url = '/api/appspath/editAppPath';
          this.$http.post(url, this.appPathInfo).then(
            res => {
              let data = res.data;
              if (data.result == '1') {
                console.log(data);
                this.showModal = false;
                this.searchEvent()
              } else {
                this.resetModalLoading()
                this.$Message.warning(data.message);
              }
            },
            error => {
              this.resetModalLoading()
              console.log(error)
              this.$Message.error('请求数据出错！');
            }
          );
        }
      },
      searchEvent: function () {
        let url = '/api/appspath/getAppPaths';
        let params = {
          searchKey: this.appName,
          state: this.status
        }
        this.$http.post(url, params).then(
          res => {
            let data = res.data;
            if (data.result == '1') {
              console.log(data);
              this.appPathList = data.data
            } else {
              this.$Message.warning(data.message);
            }
          },
          error => {
            console.log(error)
            this.$Message.error('请求数据出错！');
          }
        );
      },
      newAppPath: function () {
        this.showModal = true;
        this.modalType = '1';
        this.appPathInfo = {
          provinceId: '',
            provinceName: '',
            tag: '',
            IOSPath: '',
            IOSNeedPwd: '0',
            IOSPassword: '',
            IOSVersion: '',
            IOSUpdateTime: '',
            IOSIconUrl: '',
            IOSName: '',
            IOSShort: '',
            AndroidPath: '',
            AndroidNeedPwd: '0',
            AndroidPassword: '',
            AndroidVersion: '',
            AndroidUpdateTime: '',
            AndroidIconUrl: '',
            AndroidName: '',
            AndroidShort: '',
        }
      }
    },
    created() {},
    mounted() {
      this.tableHeight = this.$refs.tableDiv.clientHeight
      setTimeout(() => {
        this.tableShow = true;
      }, 50)
      this.searchEvent()
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" scoped type="text/stylus">
  .apppath {
    width 100%
    height 100%
    padding 20px;
    overflow hidden

    .full-content-div {
      width 100%
      height 100%
    }
  }

  .model-content {
    .info-div {
      max-height 80vh;
      overflow-y auto;
      padding-right 30px;

      .app-info {
        margin-top -10px;
        display flex;
        align-items center;
        justify-content space-between;
        padding 0 40px 20px;

        .icon {
          font-size 14px;

          img {
            display block;
            width 60px;
            height 60px;
          }
        }
      }
    }
  }
</style>